package com.baiwei.vpnapi.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @program: vpnapi
 * @description: 公共帮助函数
 * @author: Mr. Stone
 * @create: 2020-03-04 13:48
 **/
public class AppUtils {

    @Value("${smsconfig.url}")
    private static String smsUrl;

    @Value("${smsconfig.account}")
    private static String smsAccount;

    @Value("${smsconfig.apikey}")
    private static String smsApikey;

    @Value("${smsconfig.sender}")

    private static String smsSender;
    public static String generateOrder() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
        String dateString = format.format(new Date());
        int randomNum = (int)(Math.random() * 100000);
        return String.format("A%s%06d", dateString, randomNum);
    }
    public static String generateAuthCode() {
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
            for(int i=1; i<=4-randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return fourRandom;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        return ipAddress;
    }

    public static Object sendAuthCodeSms(String phone) {
        String smsContent = String.format("系统更新，请前往官网升级新版本：http://www.baidu.com");
        RestTemplate rest = new RestTemplate();
        String url = smsUrl + "?"
                + "account_name=" + smsAccount + "&"
                + "api_key=" + smsApikey + "&"
                + "sender=" + smsSender + "&"
                + "mobile=" + phone + "&"
                + "sms_content=" + smsContent;
        String result = rest.getForObject(url, String.class);
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String, Object> res = mapper.readValue(result, Map.class);
            Integer sta = (Integer)(res.get("status"));
            if(sta == 1) {
                return "success";
            } else {
                throw new RuntimeException("验证码发送错误");
            }
        } catch (JsonParseException e) {
            throw new RuntimeException("验证码发送错误");
        } catch (JsonMappingException me) {
            throw new RuntimeException("验证码发送错误");
        } catch (IOException ie) {
            throw new RuntimeException("验证码发送错误");
        }
    }


    /// mPay支付相关方法
    // 生成盐值
    public static String genSalt() {
        String salt = genSalt(16);
        return salt;
    }


    public static HashMap<String, String> platToChannel() {
        //1-android,2-ios,3-window,4-mac,5-web
        HashMap<String, String> info = new HashMap<>();
        info.put("1", "WOATQ7");
        info.put("2", "EOVKSQ");
        info.put("3", "QOEWZ3");
        info.put("4", "EOVKSQ");
        info.put("5", "QOEWZ3");
        return info;
    }

    public static String genInviteCode() {
        String salt = "";
        StringBuilder tmp = new StringBuilder(); for (char ch = '0'; ch <= '9'; ++ch)
            tmp.append(ch);
        for (char ch = 'A'; ch <= 'Z'; ++ch)
            tmp.append(ch);
        char[] symbols = tmp.toString().toCharArray(); Random random = new Random();
        char[] buf = new char[6];
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)]; salt = new String(buf);
        return salt;
    }

    private static String genSalt(int length) {
        String salt = "";
        StringBuilder tmp = new StringBuilder(); for (char ch = '0'; ch <= '9'; ++ch)
            tmp.append(ch);
        for (char ch = 'a'; ch <= 'z'; ++ch)
            tmp.append(ch);
        char[] symbols = tmp.toString().toCharArray(); Random random = new Random();
        char[] buf = new char[length];
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)]; salt = new String(buf);
        return salt; }
    /*
     * Generate hash value for payment request * with secure key
     */

    public static String genInfoString(Map<String, Object>info) {
        String res = "";
        res += info.get("salt") + ";";
        for (String key: info.keySet()){
            if(key.equals("salt") || key.equals("securekey")) {
                continue;
            }
            res += info.get(key);
        }
        res += ";" + info.get("securekey");
        res = genHashValue(res);
        return res;
    }

    public static String nowTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date());
    }

    public static String genHashValue(String plainText) {
        String hashvalue = "";
        hashvalue = hashString(plainText, "SHA-256");
        return hashvalue;
    }
    private static String hashString(String plainText, String hashType) { MessageDigest md = null;
        String hashCode = "";
        try {
            md = MessageDigest.getInstance(hashType);
            byte[] hashbyte = md.digest(plainText.getBytes("UTF-8"));
            hashCode = byte2hex(hashbyte);
        } catch (Exception ex) {
            System.out.println("Exception");
        }
        return hashCode;
    }

    private static String hexString = "0123456789ABCDEF";

    private static String byte2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0)); }
        return sb.toString();
    }

}
